<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use fast\Http;
use think\Db;
use app\api\model\Weixin;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','getphone','getuserbyphone','getglist','getgdetail','paihang'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
	//获取手机号
	public function getphone(){
		$code=$this->request->post('code');
		$site=config('site')['mini'];
		$weixin=new Weixin($site['appid'],$site['appsecret']);
		$token=$weixin->getAccessToken();
		$url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token['access_token'];
		$params = [
            'code'=>$code
        ];
		$params=json_encode($params);
		$ret = Http::sendRequest($url, $params, 'POST');
		 
        if ($ret['ret']) {
            $ar = json_decode($ret['msg'], true);
			if($ar['errcode']!==0){
				$this->error('授权失败，请重试');
			}
			if($ar['phone_info']['phoneNumber']){
				$this->getuserbyphone($ar['phone_info']['phoneNumber']);
			}else{
				$this->error('授权失败，请重试');
			}
        } 
		$this->error('授权失败，请重试');
	}
	
	public function getuserbyphone($mobile=""){
		if(empty($mobile)){
			return false;
		}
		$user=db('user')->where('mobile',$mobile)->find();
		if(empty($user)){
			//用户不存在   自动注册
			$usr['group_id']=1;
			$usr['username']="修行者";
			$usr['nickname']="修行者";
			$usr['status']="normal";
			$usr['avatar']="/static/images/fuser.png";
			$usr['mobile']=$mobile;
			$uid=db('user')->insertGetId($usr);
		}else{
			$uid=$user['id'];
		}
		$duser = $this->auth->direct($uid);
		 $data = ['userinfo' => $this->auth->getUserinfo()];
		 $this->success(__('Logged in successful'), $data); 
	}
	
	//处理图片路径 q去掉域名 a拼接域名 
	public function qdomain($img,$type="q"){
		if($type=='q'){
			if (strpos($img,request()->domain()) !== false) {
				$img=str_replace(request()->domain(),'',$img);
			}
		}else if($type=='a'){
			if (strpos($img,'/uploads/') !== false&&strpos($img,'http')===false) {
				$img=request()->domain().$img;
			}
		}else{
			$img=request()->domain().$img;
		}
		return $img;
	}
	//创建组
	public function postgroup(){
		$sdata=$this->request->post();
	
		if(empty($sdata['image'])){
			$this->error('请上传图片');
		}
		$sdata['image']=$this->qdomain($sdata['image']);
			 
		if(empty($sdata['name'])){
			$this->error('请填写名称');
		}
		if(empty($sdata['desc'])){
			$this->error('请填写简介');
		}
		if(empty($sdata['type'])){
			$this->error('请选择达成类型');
		}
		if(empty($sdata['statime'])||empty($sdata['endtime'])){
			$this->error('请选择时间');
		}
		 
		$sdata['numjson']=html_entity_decode($sdata['numjson']);
		$jingshu=json_decode($sdata['numjson'],true);
		if(empty($jingshu)){
			$this->error('请添加项目');
		}
		$tit=0;
		foreach($jingshu as $k=>$v){
			if(empty($v['tit'])||empty($v['num'])){
				$tit=1;
				break;
			}
		}
		if($tit==1){
			$this->error('请填写名称和数量');
		}
		
		if(empty($sdata['huixiang'])){
			$this->error('请填写回向文');
		}
		$sdata['user_id']=$this->auth->id;
		$sdata['createtime']=time();
		Db::startTrans();
		try {
			$gid=db('group')->insertGetId($sdata);
			 $gu['user_id']=$this->auth->id;
			 $gu['group_id']=$gid;
			 $gu['groupimage']=$this->auth->avatar;
			 $gu['groupname']=$this->auth->nickname;
			 $gu['is_guan']=1;
			 $gu['createtime']=time();
			 $guid=db('groupuser')->insertGetId($gu);
			 $jid="";
			 foreach($jingshu as $k=>$v){
				$j['group_id']=$gid;
				$j['tit']=$v['tit'];
				$j['num']=$v['num'];
				$j['createtime']=time();
				
				$jiid=db('jing')->insertGetId($j);
				$jingshu[$k]['id']=$jiid;
				$jid.=$jiid.',';
			 }
			 
			 $jid=trim($jid,',');
			  
			 $gup['numjson']=json_encode($jingshu);
			 $gup['id']=$gid;
			 $gup['jing_ids']=$jid;
			 db('group')->update($gup);
			Db::commit();
			$this->success('操作成功',$gid);
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//获取列表
	public function getglist(){
		$list=db('group')->order('switch','desc')->order('id','desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['image']=$this->qdomain($v['image'],'a');
		}
		$this->success('请求成功',$list);
	}
	//获取详情
	public function getgdetail(){
		$gid=input('gid');
		$detail=db('group')->find($gid);
		if(empty($detail)){
			$this->error('信息有误');
		}
		//获取成员
		$users=db('groupuser')->where('group_id',$gid)->orderRaw('RAND()')->limit(10)->select();
		foreach($users as $k=>$v){
			$users[$k]['groupimage']=$this->qdomain($v['groupimage'],'c');
		}
		$isin=0;
		$isguan=0;
		if($this->auth->id){
			$in=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
			if(!empty($in)){
				$isin=1;
				if($in['is_guan']==1){
					$isguan=1;
				}else{
					$isguan=0;
				}
			}	
		}
		$data['isin']=$isin;
		$data['isguan']=$isguan;
		$detail['numjson']=json_decode($detail['numjson']);
		$detail['image']=$this->qdomain($detail['image'],'a');
		
		$data['date']=date('m/d',$detail['statime']);
		$data['date1']=date('m/d',$detail['endtime']);
		
		$detail['maxtime']=($detail['statime']+(86400*60))*1000;
		$detail['statime']=$detail['statime']*1000;
		$detail['endtime']=$detail['endtime']*1000;		
		$data['detail']=$detail;
		
		$data['users']=$users;
		$this->success('请求成功',$data);
	}
	//修改组
	public function editgroup(){
		 
		$sdata=$this->request->post();
		$detail=db('group')->find($sdata['id']);
		if(empty($detail)){
			$this->error('信息有误');
		}
		$guan=db('groupuser')->where('user_id',$this->auth->id)->where('group_id',$sdata['id'])->where('is_guan',1)->find();
		if(empty($guan)){
			$this->error('无权限');
		}
		if(empty($sdata['image'])){
			$this->error('请上传图片');
		}
		$sdata['image']=$this->qdomain($sdata['image']);
		if(empty($sdata['name'])){
			$this->error('请填写名称');
		}
		if(empty($sdata['desc'])){
			$this->error('请填写简介');
		}
		if(empty($sdata['type'])){
			$this->error('请选择达成类型');
		}
		if(empty($sdata['statime'])||empty($sdata['endtime'])){
			$this->error('请选择时间');
		}
		if($sdata['statime']>$sdata['endtime']){
			$this->error('开始时间不能大于结束时间');
		}
		$sdata['numjson']=html_entity_decode($sdata['numjson']);
		$jingshu=json_decode($sdata['numjson'],true);
		if(empty($jingshu)){
			$this->error('请添加项目');
		}
		$tit=0; 
		foreach($jingshu as $k=>$v){
			$jingshu[$k]['num']=intval($v['num']);
			if(empty($v['tit'])||intval($v['num'])==0){
				$tit=1;
				break;
			}
		}
		if($tit==1){
			$this->error('请填写名称和数量');
		}
		
		if(empty($sdata['huixiang'])){
			$this->error('请填写回向文');
		}
		$sdata['numjson']=json_encode($jingshu);
		 
		$sdata['updatetime']=time();
		 
		Db::startTrans();
		try {
			
			db('group')->update($sdata);
			foreach($jingshu as $k=>$v){
				$jda['id']=$v['id'];
				$jda['num']=$v['num'];
				 
				db('jing')->update($jda);
			}
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//加入
	public function ingroup(){
		$gid=input('gid');
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
		if(!empty($ins)){
			$this->error('无需重复加入');
		}
		$in['user_id']=$this->auth->id;
		$in['group_id']=$gid;
		$in['groupimage']=$this->auth->avatar;
		$in['groupname']=$this->auth->nickname;
		$in['createtime']=time();
			 
		Db::startTrans();
		try {
			db('groupuser')->insertGetId($in);
			Db::commit();
			$this->success('加入成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//退出
	public function outgroup(){
		$gid=input('gid');
		$group=db('group')->find($gid);
		if($group['user_id']==$this->auth->id){
			$this->error('创建者不能退出');
		}
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
		if(empty($ins)){
			$this->error('信息有误');
		}
		Db::startTrans();
		try {
			db('groupuser')->delete($ins['id']);
			Db::commit();
			$this->success('退出成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//获取信息
	public function getguser(){
		$gid=input('gid');
		$uid=input('uid');
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$uid)->find();
		$ins['groupimage']=$this->qdomain($ins['groupimage'],'c');
		$group=db('group')->find($gid);
		if(empty($ins)){
			$this->error('信息有误');
		}
		$isguan=0;
		$uguan=0;
		$guans=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->where('is_guan',1)->find();
		$uguans=db('groupuser')->where('group_id',$gid)->where('user_id',$uid)->where('is_guan',1)->find();
		if(!empty($uguans)){
			$uguan=1;
		} 
		if(!empty($guans)){
			$isguan=1;
		} 
		if($group['user_id']==$this->auth->id){
			$isguan=2;
		}
		$data['uguan']=$uguan;
		$data['isguan']=$isguan;
		$data['user']=$ins;
		$this->success('请求成功',$data); 
	}
	//成员列表
	public function getulist(){
		$gid=input('gid');
		$list=db('groupuser')->where('group_id',$gid)->order('is_guan','desc')->order('id','desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['groupimage']=$this->qdomain($v['groupimage'],'c');
		}
		$this->success('请求成功',$list);
	}
	
	
	//删除
	public function delguser(){
		$gid=input('gid');
		 
		$uid=input('uid');
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$uid)->find();
		if(empty($ins)){
			$this->error('信息有误');
		}
		$isguan=0;
		$uguan=0;
		$guans=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->where('is_guan',1)->find();
		 
		if(!empty($ins['is_guan']==1)){
			$uguan=1;
		} 
		if(!empty($guans)){
			$isguan=1;
		} 
		if($group['user_id']==$this->auth->id){
			$isguan=2;
		}
		if($uid==$this->auth->id){
			$this->error('无权限');
		}
		if($isguan<=$uguan){
			$this->error('无权限');
		}
		Db::startTrans();
		try {
			db('groupuser')->delete($ins['id']);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
	//设置取消 管理
	public function setguan(){
		$gid=input('gid');
		$uid=input('uid');
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		
		if($group['user_id']!=$this->auth->id){
		 	$this->error('无权限');
		}
		if($this->auth->id==$uid){
			$this->error('无权限');
		}
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$uid)->find();
		if(empty($ins)){
			$this->error('信息有误');
		}
		$ins['is_guan']=!$ins['is_guan'];
		Db::startTrans();
		try{
			db('groupuser')->update($ins);
			Db::commit();
			$this->success('操作成功');
		}catch(Exception $e){
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//获取组内资料
	public function getgname(){
		$gid=input('gid');
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		$ins['groupimage']=$this->qdomain($ins['groupimage'],'c');
		$this->success('请求成功',$ins);
	}
	//资料 
	public function setgname(){
		$sdata=$this->request->post();
		 
		if(empty($sdata['gid'])){
			$this->error('信息有误1');
		}
		$group=db('group')->find($sdata['gid']);
		if(empty($group)){
			$this->error('信息有误2');
		}
		$ins=db('groupuser')->where('group_id',$sdata['gid'])->where('user_id',$this->auth->id)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		if(empty($sdata['groupname'])){
			$this->error('请填写名字');
		}
		$ins['groupname']=$sdata['groupname'];
		if(empty($sdata['groupimage'])){
			$this->error('请上传头像');
		}
		$ins['groupimage']=$sdata['groupimage'];
		$ins['groupimage']=$this->qdomain($sdata['groupimage'],'q');
		Db::startTrans();
		try {
			db('groupuser')->update($ins);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//获取今日报数情况
	public function getjing(){
		$gid=input('gid');
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		//$this->auth->id
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		
		$list=db('jing')->where('group_id',$gid)->select();
		foreach($list as $k=>$v){
			$gids[]=$v['id'];
		}
		$today = date('Y-m-d');  
		$start = strtotime($today);  
		$bao=db('grouplog')->where('jing_id','in',$gids)->where('createtime','>',$start)->column('num','jing_id');;
		foreach($list as $k=>$v){
			$list[$k]['bnum']=$bao[$v['id']]??0; 
		}
		$data['time']=date("Y年m月d日");
		$data['list']=$list;
		$this->success('请求成功',$data);
	}
	//报数  
	public function baoshu(){
		$sdata=$this->request->post('data');
		$sdata=html_entity_decode($sdata);
		$sdata=json_decode($sdata,true);
		$gid=$sdata[0]['group_id'];
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		$uid=$this->auth->id;
		 
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$uid)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
	    foreach($sdata as $k=>$v){
			$jids[]=$v['id'];
		}
		$today = date('Y-m-d');  
		$start = strtotime($today);  
		Db::startTrans();
		try {
			db('grouplog')->where('group_id',$gid)->where('user_id',$uid)->where('jing_id','in',$jids)->where('createtime','>',$start)->delete();
			foreach($sdata as $k=>$v){
				db('grouplog')->insert(
					array(
						"inid"=>$ins['id'],
						"group_id"=>$gid,
						"user_id"=>$uid,
						"jing_id"=>$v['id'],
						"num"=>$v['bnum'],
						"createtime"=>time()
					)
				);
			}
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	//统计
	public  function getlogs(){
		$gid=input('gid');
		$group=db('group')->find($gid);
		if(empty($group)){
			$this->error('信息有误');
		}
		//$this->auth->id
		$ins=db('groupuser')->where('group_id',$gid)->where('user_id',$this->auth->id)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		$list=db('jing')->where('group_id',$gid)->select();
		$jid=input('jid')??$list[0]['id'];
		$logdata=db('grouplog')
					->alias('log')
					->where('jing_id',$jid)
					->field('user.*,log.num,log.inid,log.jing_id,log.createtime,DATE_FORMAT(FROM_UNIXTIME(log.createtime), "%Y-%m-%d") as day')
					->join('groupuser user','user.id=log.inid')
					->order("log.id desc,log.createtime desc")
					->select();
		foreach($logdata as $k=>$v){
			$v['groupimage']=$this->qdomain($v['groupimage'],'c');
			$logs[$v['day']][]=$v;
		}
		arsort($logs);
		$data['jing']=db('jing')->find($jid);
		$data['sum']=db('grouplog')->where('jing_id',$jid)->sum('num');
		$data['logs']=$logs;
		$this->success('请求成功',$data);
	}
	public function getinfo(){
		$user = $this->auth->getUser();
		$user->avatar=$this->qdomain($user->avatar,'c');
		$this->success('请求成功',$user);
	} 
	public function mygroup(){
		$uid=$this->auth->id;
		$group=db('groupuser')
			->field('group.name,group.id,group.image,group.desc,users.group_id,users.is_guan')
			->alias('users')
			->where("users.user_id",$uid)
			->join('group','users.group_id=group.id')
			->order("users.is_guan desc,group.id desc")
			->select();
		foreach($group as $k=>$v){
			$group[$k]['image']=$this->qdomain($v['image'],'a');
		}
		$data['list']=$group;
		$this->success('请求成功',$data);
	}
	//资料 
	public function setuname(){
		$sdata=$this->request->post();

		if(empty($sdata['nickname'])){
			$this->error('请填写名字');
		}
		 
		if(empty($sdata['avatar'])){
			$this->error('请上传头像');
		}
		 
		$sdata['avatar']=$this->qdomain($sdata['avatar'],'q');
		Db::startTrans();
		try {
			db('user')->update($sdata);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	
	public function paihang(){
		$jid=intval(input('jid'));
		if($jid==0){
			$this->error('参数有误');
		}
		$map['log.jing_id']=$jid;
		$type=input('type');
		
		if($type=="m"){
			//月排行
			$start=mktime(0,0,0,date('m'),1,date('Y'));  
			$end=mktime(23,59,59,date('m'),date('t'),date('Y'));
			$map['log.createtime']=array('between',array($start,$end));
		}elseif($type=="w"){
			//周排行
			$start= mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
			$end= mktime(0,0,0,date('m'),date('d')-date('w')+7,date('y'));
			$map['log.createtime']=array('between',array($start,$end));
		}
		//无type参数 总排行
		$list=db('grouplog')
			->where($map)
			->alias('log')
			->field('log.num, log.jing_id, SUM(log.num) as sums,log.user_id,user.groupname,user.groupimage')
			->join('groupuser user', 'user.id = log.inid')
			->group('log.user_id')
			->order('sums', 'DESC')
			->limit(10)->select();
		foreach($list as $k=>$v){
			$list[$k]['groupimage']=$this->qdomain($v['groupimage'],'c');
		}
		$this->success('请求成功',$list);
	}
	
	public function getulog(){
		$uid=input('uid');
		$jid=input('jid');
		$jing=db('jing')->find($jid);
		//$this->auth->id
		$ins=db('groupuser')->where('group_id',$jing['group_id'])->where('user_id',$uid)->find();
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		$ins['groupimage']=$this->qdomain($ins['groupimage'],'c');
		$quan=db('groupuser')->where('group_id',$jing['group_id'])->where('user_id',$this->auth->id)->find();
		if($quan['is_guan']<=0){
			$this->error('无权限');
		}
		$time=input('time');
		$statime=strtotime($time);
		$endtime=$statime+86400;
		$shu=db('grouplog')->where('jing_id',$jid)->where('user_id',$uid)->where('createtime','between',array($statime,$endtime))->find();
		$data['shu']=$shu;
		$data['ins']=$ins;
		$data['jing']=$jing;
		$this->success('请求成功',$data);
	}
	
	public function setulog(){
		$sdata=$this->request->post();
		$jing=db('jing')->find($sdata['jid']);
		//$this->auth->id
		$ins=db('groupuser')->where('group_id',$jing['group_id'])->where('user_id',$sdata['uid'])->find();
		 
		if(empty($ins)){
			$this->error('未加入该群组');
		}
		$quan=db('groupuser')->where('group_id',$jing['group_id'])->where('user_id',$this->auth->id)->find();
		if($quan['is_guan']<=0){
			$this->error('无权限');
		} 
		$shu=db('grouplog')->find($sdata['lid']);
		if(empty($shu)){
			$this->error('信息有误');
		}
		$shu['num']=$sdata['num'];
		Db::startTrans();
		try {
			db('grouplog')->update($shu);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
}
